<template>
  <div class="order-form-testee-form-extend-upload">
    <a-row>
      <a-col :span="19" :offset="1">
        <a-upload
          name="file"
          :multiple="true"
          :fileList="data"
          :beforeUpload="beforeUpload"
          :remove="handleRemove"
        >
          <a-button> <a-icon type="upload" /> 请上传 </a-button>
          <span class="cg-label">（单个文件最大10MB）</span>
        </a-upload>      
      </a-col>
    </a-row>

 
  </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid';

export default {
  props: {
    value: { type: [Array], },
  },
  watch: {
    value() {
      this.data = this.getData()
    },
  },
  data() {
    return {
      data: this.getData()
    }
  },
  methods: {
    getData() {
      if (!this.value) {
        return []
      }
      let jsonStr = JSON.stringify(this.value)
      let data = JSON.parse(jsonStr)

      // get fileMap
      let fileMap = {}
      this.value.forEach(item => {
        fileMap[item.uid] = item.file
      })

      // JSON.parse will toString file object, need set file object again
      data.forEach(item => {
        if (item.file) {
          item.file = fileMap[item.uid]
        }
      })
      return data;
    },
    handleRemove(file) {
      let index = this.data.findIndex(item => item.uid == file.uid)
      this.data.splice(index, 1)
      this.$emit('change', this.data)
    },
    beforeUpload(file) {
      //避免走action,缓存file

      if (file.size / 1024 / 1024 > 10 ) {
        this.$message.error('文件过大（超过10MB），无法上传！');
        return false
      }

      this.data.push({
        uid: uuidv4().replace(/-/g, ''),
        name: file.name,
        file: file,
        fileType: this.fileType,
      })
      this.$emit('change', this.data)

      return false
    },
  }
}
</script>
<style>
.order-form-testee-form-extend-upload .file-type {
  height: 22px;
  line-height: 22px;
  margin-top: 8px;
  text-align: right;
}
</style>
